const Koa = require('koa')
const Routor = require('koa-router')
const mongoose = require('mongoose')
const bodyParser = require('koa-bodyparser')
const passport = require('koa-passport')

const app = new Koa()
app.use(bodyParser())
app.use(passport.initialize())
app.use(passport.session())
require('./config/passport')(passport)





const router = new Routor()
const dbUrl = require('./config/keys').mongoURI
const port = process.env.port || 3000

// 数据库连接
mongoose.connect(dbUrl, {useUnifiedTopology: true, useNewUrlParser: true}).then(() => {
  console.log('数据库链接成功');
}).catch(err => {
  console.log(err);
})


// 引入路由
const users = require('./routers/api/users')

// 中间件 打印url
app.use(async (ctx, next) => {
  console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
  await next(); // 调用下一个middleware
});

// 中间件 打印耗时
app.use(async (ctx, next) => {
  const start = new Date().getTime(); // 当前时间
  await next(); // 调用下一个middleware
  const ms = new Date().getTime() - start; // 耗费时间
  console.log(`Time: ${ms}ms`); // 打印耗费时间

});

router.use('/api/users', users)

// 配置路由
app.use(router.routes()).use(router.allowedMethods())


app.listen(port, () => {
  console.log(`server started on ${port}`);
})
